import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import HomeView from '@/views/Home.vue'
import Layout from '@/layout/Index.vue'
import { whiteList } from "@/config";
import { isLogin } from "@/utils";
import { useUser } from "@/store/user";
import Axios from "axios";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    path: "/",
    name: "home",
    component: Layout,
    children: [
      {
        path: "/home",
        component: HomeView,
      },
    ],
  },
  {
    path: "/about",
    name: "about",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import("../views/AboutView.vue"),
  },
  {
    path: "/404",
    component: () => import("../views/NotFound.vue"),
  },
  {
    path: "/login",
    name: "login",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/login.vue"),
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});
// 加载views下的所有组件到模块
const modules = (import.meta as any).glob('../views/**/*.vue');

function asyncRoutesHandler(routes: any[]) {
  return routes.map((route: any) => {
    // 判断component是否是Layout
    if (route.component === 'Layout') {
      route.component = Layout;
    } else {
      // import: 基于webpack编译原则, 有变量会提前解析
      const compPath = route.component;
      // 没有变量, 作为${route.component}直接使用
      // route.component = () => import(`@/views/${compPath}.vue`);

      // Vite动态加载
      route.component = modules[`../views/${compPath}.vue`];
    }
    // 如果有children 继续递归处理
    if (route.children) {
      route.children = asyncRoutesHandler(route.children);
    }
    return route;
  });
}
async function loadMenus(to: any, next: any) {
  const user = useUser();
  // 发起请求
  const res = await Axios.get("/menus.json");
  //赋值pinia中的menus 避免反复执行加载菜单
  user.setMenus(res.data);
  // 新路由
  const asyncRoutes = asyncRoutesHandler(res.data);
  console.log(res.data, "菜单::", asyncRoutes);
  // 加入到路由中
  asyncRoutes.forEach((r) => {
    router.addRoute(r);
  });
  // 404的处理一定要放到最后
  router.addRoute({ path: "/:catchAll(.*)", redirect: "/404" });

  // 这次无效的导航 要重新来过
  next({ ...to, replace: true /*不额外向历史记录添加一条访问记录*/ });
}
router.beforeEach((to, from, next) => {
  const user = useUser();
  // 白名单               // /login
  if (whiteList.includes(to.path)) {
    return next();
  }
  // 判断是否登录
  if (!isLogin()) {
    // to.path: /dasdsadsadsad/dsadasdsa?id=1
    return next("/login?redirect=" + to.path);
  }
  // 登录后, 是否已经有动态菜单
  if (user.menus.length === 0) {
    return loadMenus(to, next);
  }
  console.log("最后放行...");
  // 有菜单
  next();
});

export default router
